<template>
  <div class="author" ref="scrollContainer">
    <!-- 加载中提示 -->
    <van-loading v-if="isLoading && authorData.length === 0" type="spinner" color="#1989fa" vertical>
      加载中...
    </van-loading>

    <!-- 无数据提示 -->
    <van-empty v-else-if="!isLoading && authorData.length === 0 && searchQuery" description="暂无数据" />

    <!-- 数据列表 -->
    <div class="author-container" v-if="authorData.length > 0">
      <div class="author-item" v-for="item in authorData" :key="item.content_id">
        <div class="item-img" :style="{ backgroundImage: 'url(' + item.cover + ')' }"></div>
        <div class="item-info">
          <div class="info-title">{{ item.title }}</div>
          <div class="info-desc">{{ item.subtitle }}</div>
        </div>
      </div>
    </div>

    <!-- 底部加载更多提示 -->
    <div class="load-more" v-if="isLoading && authorData.length > 0">
      <van-loading type="spinner" size="16px" color="#1989fa">加载中...</van-loading>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { searchAuthor } from '../../api/api';

export default {
  data() {
    return {
      authorData: [],// 页面数据
      currentPage: 0, // 当前页码
      hasMore: true, // 是否还有更多数据
      lastTriggerTime: 0, // 最后一次触发时间
      isLoading: false // 是否正在加载中
    }
  },
  computed: {
    ...mapState(['searchQuery'])
  },
  watch: {
    // 监听搜索关键词变化，重新请求数据
    searchQuery: {
      immediate: true, // 初始加载时执行一次
      handler() {
        // 重置状态
        this.currentPage = 0;
        this.authorData = [];
        this.hasMore = true;
        this.fetchAuthorData();
      }
    }
  },
  mounted() {
    // 添加滚动监听
    this.$refs.scrollContainer.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    // 移除滚动监听
    if (this.$refs.scrollContainer) {
      this.$refs.scrollContainer.removeEventListener('scroll', this.handleScroll);
    }
  },
  methods: {
    // 初始化获取3组数据
    async fetchAuthorData() {
      if (!this.searchQuery || !this.hasMore) return;

      this.isLoading = true;

      try {
        // 生成3个请求的Promise
        const requests = Array.from({ length: 3 }, (_, i) =>
          searchAuthor(this.searchQuery, this.currentPage + i)
            .then(res => res.data?.list || []) // 单个请求的响应处理
        );

        // 等待所有请求完成
        const allLists = await Promise.all(requests);
        this.currentPage += 3;

        const hasEmpty = allLists.some(list => list.length === 0);
        if (hasEmpty) {
          this.hasMore = false;
          if (this.authorData.length > 0) {
            this.$toast({
              message: '没有更多了~',
              position: 'bottom',
            });
          }
        }

        // 转化为一维数组，合并所有数据
        this.authorData = [...this.authorData, ...allLists.flat()];
      }
      catch (error) {
        // 统一捕获所有请求的错误
        console.error('获取数据失败:', error);
        this.authorData = [];
      } finally {
        this.isLoading = false;
      }

    },

    // 处理滚动事件
    handleScroll() {
      const container = this.$refs.scrollContainer;
      // 判断是否滚动到底部
      const isBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 10;

      if (isBottom && this.hasMore && !this.isLoading) {
        const now = Date.now();
        // 限制1秒内只能触发一次
        if (now - this.lastTriggerTime > 1000) {
          this.lastTriggerTime = now;
          this.loadMoreData();
        }
      }
    },

    async loadMoreData() {
      if (!this.searchQuery || !this.hasMore) return;

      this.isLoading = true;
      try {
        const res = await searchAuthor(this.searchQuery, this.currentPage);
        const list = res.data?.list || [];

        if (list.length === 0) {
          this.hasMore = false;
          this.$toast({
            message: '没有更多了~',
            position: 'bottom',
          });
        } else {
          this.authorData = [...this.authorData, ...list];
          this.currentPage++;
        }
      } catch (error) {
        console.error('加载更多失败:', error);
      } finally {
        this.isLoading = false;
      }
    }
  }
}
</script>

<style scoped lang="less">
.author {
  width: 100vw;
  height: 100%;
  box-sizing: border-box;
  overflow-x: hidden;
  overflow-y: auto;
}

.author-container {
  width: 100%;
  padding: 0 1vw 5vh;
  box-sizing: border-box;
  background-color: #fff;

  .author-item {
    width: 100%;
    height: 5vh;
    display: flex;
    align-items: center;
    gap: 2vw;
    padding-bottom: 2vh;
    margin-bottom: 2vh;
    border-bottom: 1px solid #f5f5f5;

    .item-img {
      height: 100%;
      aspect-ratio: 1/1;
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 50%;
    }

    .item-info {
      width: 100%;
      font-size: 10px;
      height: 90%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .info-title {
        width: 80%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .info-desc {
        font-size: 8px;
        color: #bbb;
      }
    }
  }
}

.load-more {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2vh 0;
}
</style>
